package it.camelotone.ejb.entity;

import it.camelotone.ejb.session.BillingPersistenceService;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.embeddable.EJBContainer;
import javax.naming.NamingException;

import junit.framework.TestCase;

public class ServiceBillTestCase extends TestCase {
	
	private EJBContainer container;

	@Override
	protected void setUp() throws Exception {
		Map<String, Object> properties = new HashMap<String, Object>();
		properties.put(EJBContainer.MODULES, new File("target/classes"));
		properties.put("org.glassfish.ejb.embedded.glassfish.instance.root", "/Users/fabiomassimo/glassfish3/glassfish/domains/camelone");
	    container = EJBContainer.createEJBContainer(properties);
	}
	
	public void testAddBill() throws Exception {
		ServiceBill serviceBill = new ServiceBill();
		serviceBill.setDateOfService(new Date());
		Calendar cal = Calendar.getInstance(); 
		cal.add(Calendar.MONTH, 1);
		serviceBill.setDueDate(cal.getTime());
		serviceBill.setProviderName("ATT");
		serviceBill.setDescriptionOfService("Cell Phone");
		BillingPersistenceService bps = (BillingPersistenceService) getBean("BillingPersistenceService");
		assertNotNull(bps);
		bps.addBill(serviceBill);
		assertNotNull(serviceBill.getId());
		assertFalse(serviceBill.isLate());
	}
	
	public void testRemoveBill() throws Exception {
		ServiceBill serviceBill = new ServiceBill();
		serviceBill.setDateOfService(new Date());
		Calendar cal = Calendar.getInstance(); 
		cal.add(Calendar.MONTH, 1);
		serviceBill.setDueDate(cal.getTime());
		serviceBill.setProviderName("ATT");
		serviceBill.setDescriptionOfService("Cell Phone");
		BillingPersistenceService bps = (BillingPersistenceService) getBean("BillingPersistenceService");
		assertNotNull(bps);
		bps.addBill(serviceBill);
		assertNotNull(serviceBill.getId());
		bps.removeBill(serviceBill.getId());
	}

	private Object getBean(String bean) throws NamingException {
		return container.getContext().lookup("java:global/classes/" + bean);
	}

	@Override
	protected void tearDown() throws Exception {
		if (container == null)
			return;
		
		container.close();
		container = null;
	}

}
